﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SmartSpace.WebApp._console.page
{
    public partial class template_edit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            _ctlHiddenName.Value = Request.QueryString["name"];

            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                PageTemplate template = service.GetPageTemplate(_ctlHiddenName.Value);

                _ctlEditName.Text = template.Code;

                _ctlPreviewImage.ImageUrl = string.Format("~/_handlers/_private/get-image.ashx?id={0}", template.PreviewImageId);
                _ctlLinkFile.HRef = string.Format("~/_handlers/_private/get-page-tplt.ashx?id={0}", template.Id);
                _ctlLinkFile.InnerHtml = string.Format("<img src='../resources/images/pages/tplt-single.png'/>{0}", template.Code);
            }

            _ctlLinkBack.NavigateUrl = "./Template-list.aspx";
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();

            PageTemplate template = service.GetPageTemplate(_ctlHiddenName.Value);

            if (_ctlNewPreviewImage.HasFile)
            {
                SmartSpace.Core.Image image = new SmartSpace.Core.Image();
                image.Id = Guid.NewGuid();
                image.Data = _ctlNewPreviewImage.FileBytes;
                image.Extension = new FileInfo(_ctlNewPreviewImage.FileName).Extension;

                if (service.SaveImage(image))
                {
                    template.PreviewImageId = image.Id;
                }
                else
                {
                    return;
                }
            }

            if (_ctlFileUpload.HasFile)
            {
                template.Data = _ctlFileUpload.FileBytes;
            }
            if (service.SavePageTemplate(template))
            {
                System.IO.File.WriteAllBytes(Server.MapPath("~/_templates/_page/" + template.Code + ".ascx"), template.Data);

                Response.Redirect(_ctlLinkBack.NavigateUrl);
            }
        }
    }
}